package com.mgkj.service.impl;



import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mgkj.base.HttpResult;
import com.mgkj.common.result.Result;
import com.mgkj.common.utils.HttpClientUtil;
import com.mgkj.common.utils.TimeUtils;
import com.mgkj.dto.All;
import com.mgkj.dto.KWAndNum;
import com.mgkj.dto.MOCTGDto;
import com.mgkj.dto.yf.InitLldDto;
import com.mgkj.dto.yf.InitLldList;
import com.mgkj.entity.*;
import com.mgkj.entity.yf.*;
import com.mgkj.mapper.*;
import com.mgkj.service.CommonService;
import com.mgkj.service.MoService;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class MoServiceImpl implements MoService {

    @Resource
    private MoctfMapper moctfMapper;
    @Resource
    private DscmbMapper dscmbMapper;
    @Resource
    private MoctgMapper moctgMapper;
    @Resource
    private CommonService commonService;
    @Resource
    private CommonMapper commonMapper;
    @Resource
    private InvmbMapper invmbMapper;
    @Resource
    private MoctaMapper moctaMapper;
    @Resource
    private LogisticsMapper logisticsMapper;

    @Resource
    private InitMoctcMapper initMoctcMapper;
    @Resource
    private InitMocteMapper initMocteMapper;
    @Resource
    private InitAdmmfMapper initAdmmfMapper;
    @Resource
    private InitCmsmqMapper initCmsmqMapper;
    @Resource
    private InitCmsmdMapper initCmsmdMapper;
    @Resource
    private InitMoctbMapper initMoctbMapper;
    @Resource
    private InvmcMapper invmcMapper;

    @Resource
    private WmsInvmlMapper wmsInvmlMapper;

    @Resource
    private WmsInvlaMapper wmsInvlaMapper;

    @Override
    @DSTransactional
    public Result insertAll(All all){
        DynamicDataSourceContextHolder.push(all.getCompany());
        boolean flag = false;
        Moctf moctf = new Moctf();
        String dh = all.getTF002();
        String TF003 = all.getTF003();
        String creator = all.getTF013();
        String usrGroup = commonMapper.getUsrGroup(creator);
        Integer count1 = moctfMapper.selectCount(new QueryWrapper<Moctf>()
                .eq("TF001", all.getTF001())
                .eq("TF002", all.getTF002())
                .eq("TF006", "Y"));
        if (count1 >= 1) {
            return Result.fail().message("此单别单号存在并存在审核单据,请更换单号或手动在易飞删除单据！");
        }
        Dscmb dscmb = dscmbMapper.selectOne(new QueryWrapper<Dscmb>().eq("MB003", all.getCompany()));
        String company = dscmb.getMB001().trim();
        Integer count2 = moctfMapper.selectCount(new QueryWrapper<Moctf>()
                .eq("TF001", all.getTF001())
                .eq("TF002", all.getTF002())
                .eq("TF006", "N"));
        if (count2 >= 1) {
            dh = all.getTF002();
            moctfMapper.delete(new QueryWrapper<Moctf>()
                    .eq("TF001", all.getTF001())
                    .eq("TF002", all.getTF002()));
            moctgMapper.delete(new QueryWrapper<Moctg>()
                    .eq("TG001", all.getTF001())
                    .eq("TG002", all.getTF002()));
        }
        else {
            Integer count3 = moctfMapper.selectCount(new QueryWrapper<Moctf>()
                    .eq("UDF12", all.getTF002()));
            if (count3 >= 1) {
                return Result.fail().message("此单号已存在!");
            } else {
                flag = true;
//                dh = commonService.getIdByType(all.getTF001(), "MOCTF");
                moctf.setUdf12(all.getTF002());
            }
        }
        Double zRKSL = 0.0;
        Double zYSSL = 0.0;
        Double zBFSL = 0.0;
        Double zPHSL = 0.0;
        Double zYTSL = 0.0;
        Double zRKBZSL = 0.0;
        Double zYSBZSL = 0.0;
        Double zBFBZSL = 0.0;
        Double zPHBZSL = 0.0;
        Double zYTBZSL = 0.0;

        moctf.setTf001(all.getTF001());
        List<MOCTGDto> moctgList = all.getMoctgList();
        List<Moctg> moctgs = new ArrayList<>();

        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();

        // 定义日期时间格式
        DateTimeFormatter formatter17 = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        DateTimeFormatter formatter8 = DateTimeFormatter.ofPattern("yyyyMMdd");

        // 格式化时间
        String formattedTime17 = currentTime.format(formatter17);
        String formattedTime8 = currentTime.format(formatter8);
        System.out.println("formattedTime17"+ formattedTime17);
        //入库时间由员工选的特判
        DateTimeFormatter formatter18 = DateTimeFormatter.ofPattern("HHmmssSSS");
        String formattedTime18 = TF003 + currentTime.format(formatter18);
        System.out.println("formattedTime18" + formattedTime18);

        moctf.setTf002(dh);

        moctf.setCreator(creator);
        moctf.setCompany(company);
        moctf.setUsrGroup(usrGroup);
        moctf.setCreateDate(formattedTime18);
        moctf.setFlag(1.0);

        moctf.setTf003(all.getTF003().substring(0, 8));
        for (MOCTGDto moctgDto : moctgList) {
            moctgDto.setCompany(company);
            moctgDto.setCreator(creator);
            moctgDto.setUsrGroup(usrGroup);
            moctgDto.setInsertMoDate(TF003);
            Moctg moctg = new Moctg();
            moctg.setCompany(company);
            moctg.setCreator(creator);
            moctg.setUsrGroup(usrGroup);
            moctg.setCreateDate(formattedTime18);
            moctg.setFlag(1.0);
            moctg.setTg001(moctgDto.getTG001());
            moctg.setTg002(dh);
            moctg.setTg003(moctgDto.getTG003());
            moctg.setTg004(moctgDto.getTG004());
            Invmb invmb = invmbMapper.selectOne(new QueryWrapper<Invmb>().eq("MB001", moctgDto.getTG004()));
            if (invmb == null) return Result.fail().message("此品号不存在!");
            moctg.setTg005(invmb.getMb002());
            moctg.setTg006(invmb.getMb003());
            moctg.setTg007(moctgDto.getTG007());
            moctg.setTg009(moctgDto.getTG009());
            moctg.setTg010(moctgDto.getTG010());
            moctg.setTg011(moctgDto.getTG011());
            zRKSL += moctgDto.getTG011();
            moctg.setTg013(moctgDto.getTG013());
            zYSSL += moctgDto.getTG013();
            moctg.setTg014(moctgDto.getTG014());
            moctg.setTg015(moctgDto.getTG015());

            Mocta mocta = moctaMapper.selectOne(new QueryWrapper<Mocta>()
                    .eq("TA001", moctgDto.getTG014())
                    .eq("TA002", moctgDto.getTG015()));

            if (mocta == null) {
                return Result.fail("工单不存在!").message("工单不存在!");
            }

            moctg.setTg016(moctgDto.getTG016());
            //批号
            if(moctgDto.getTG017() == null){
                moctg.setTg017("********************");
            }else {
                moctg.setTg017(moctgDto.getTG017());
            }
            moctg.setTg020(moctgDto.getTG020());
            moctg.setTg021("********************");
            moctg.setTg022(moctgDto.getTG022());

            moctg.setTg024(mocta.getTa044());

            //包装单位
            moctg.setTg029(mocta.getTa048());
            moctg.setTg030(TF003);
//            moctg.setTg030(formattedTime8);
//            moctg.setTgc01(mocta.getTac01());

            moctg.setTg034(0.0000);
            moctg.setTg035("N");
            moctg.setTg036("##########");
            moctg.setTg037(mocta.getTa007());
            moctg.setTg038(moctgDto.getTG013());
            //最大入库数量
            Double maxtg011 = logisticsMapper.selectmax(moctgDto.getTG004(), moctgDto.getTG014(), moctgDto.getTG015());
            if (maxtg011 == null) {
                return Result.fail("工单品号和输入工单对应不上!").message("工单品号和输入工单对应不上!");
            }
            if (moctg.getTg011() > maxtg011) {
                // moctg.getTG011() 大于 maxtg011
                return Result.fail("输入的数量超过最大入库数量!").message("输入的数量超过最大入库数量!");
            }
            moctgs.add(moctg);
        }
        //1  SELECT * FROM CMSMB  只有编号1的工厂 暂时写死
        moctf.setTf004(all.getTF004());
        moctf.setTf005(all.getTF005());

        moctf.setTf006(all.getTF006());
        moctf.setTf007("N");
        moctf.setTf008(0.0);
        moctf.setTf009("N");
        moctf.setTf010("N");
        //工作中心只有一个 暂时写死
        moctf.setTf011(all.getTF011());
        moctf.setTf012(TF003);
//        moctf.setTf012(formattedTime8);
        moctf.setTf013(creator);
        moctf.setTf014("N");
        //总入库数量
        moctf.setTf023(zRKSL);
        //总验收数量
        moctf.setTf024(zYSSL);
        //总报废数量
        moctf.setTf025(zBFSL);
        //总破坏数量
        moctf.setTf026(zPHSL);
        //总验退数量
        moctf.setTf027(zYTSL);
        //总入库包装数量
        moctf.setTf028(zRKBZSL);
        //总验收包装数量
        moctf.setTf029(zYSBZSL);
        //总报废包装数量
        moctf.setTf030(zBFBZSL);
        //总破坏包装数量
        moctf.setTf031(zPHBZSL);
        //总验退包装数量
        moctf.setTf032(zYTBZSL);

        moctfMapper.insert(moctf);

        for (Moctg moctg : moctgs) {
            moctgMapper.insert(moctg);
        }

        Integer i = moctgMapper.selectCount(new QueryWrapper<Moctg>()
                .eq("TG001", all.getTF001())
                .eq("TG002", dh));
        if (i == null || i <= 0) {
            moctfMapper.delete(new QueryWrapper<Moctf>()
                    .eq("TF001", all.getTF001())
                    .eq("TF002", dh));
            return Result.fail("单身生成失败!").message("单身生成失败!");
        }

        //调用审核员

        //插入wmsl两表
        Boolean b=this.wmsinsertmoctg(moctgList);
        if (!b) {
            moctgMapper.delete(new QueryWrapper<Moctg>().eq("TG001",all.getTF001()).eq("TG002",dh));
            moctfMapper.delete(new QueryWrapper<Moctf>().eq("TF001",all.getTF001()).eq("TF002",dh));

            return Result.fail("wms_invla和wms_invml插入失败！").message("wms_invla和wms_invml插入失败！");
        }


        return Result.ok("生产入库单据生成成功:" + all.getTF001() + '-' + dh).message("单据生成成功!");
    }

    @Transactional
    public Boolean wmsinsertmoctg(List<MOCTGDto> moctgs){
        List<WmsInvml> invmlList=new ArrayList<>();
        List<WmsInvla> wmsInvlas=new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式

//        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("HHmmssSSS");
        // 将 LocalDateTime 对象格式化为字符串
        String formattedDateTime = now.format(formatter2);
        String TF003 = moctgs.get(0).getInsertMoDate();
        formattedDateTime = TF003 + formattedDateTime;
        System.out.println("插入wms两表的create_date" + formattedDateTime) ;
        boolean result=true;
        for (MOCTGDto moctg : moctgs){
            //库位可以不存在
            if (moctg.getKwInfo() == null || moctg.getKwInfo().isEmpty()) {
                result = insertByKw(TF003,formattedDateTime,moctg,invmlList,wmsInvlas);
            } else {
                for (KWAndNum kwAndNum : moctg.getKwInfo()) {
                    moctg.setTG036(kwAndNum.getKw());
                    moctg.setTG013(kwAndNum.getNum());
                    moctg.setTG011(kwAndNum.getNum());
                    result = insertByKw(TF003,formattedDateTime,moctg,invmlList,wmsInvlas);
                    if (!result) return result;
                }
            }
            if (!result) return result;
        }
        return result;
    }





    @Override
    public Result saveMaterialRequisition(InitLldDto initLldDto) throws UnknownHostException {
        DynamicDataSourceContextHolder.push(initLldDto.getCompany());
        boolean flag1 = false;
        // 3.领料单单身信息创建
        InitMoctc initMoctc = new InitMoctc();
        String dh = "";
        Integer count4 = initMoctcMapper.selectCount(new QueryWrapper<InitMoctc>()
                .eq("TC001", initLldDto.getTC001())
                .eq("TC002", initLldDto.getTC002())
                .eq("TC009", "Y"));
        if (count4 >= 1) {
            return Result.fail("此单别单号存在并存在审核单据,请更换单号或手动在易飞删除单据");
        }
        Dscmb dscmb = dscmbMapper.selectOne(new QueryWrapper<Dscmb>().eq("MB003", initLldDto.getCompany()));
        String company = dscmb.getMB001().trim();
        Integer count1 = initMoctcMapper.selectCount(new QueryWrapper<InitMoctc>()
                .eq("TC001", initLldDto.getTC001())
                .eq("TC002", initLldDto.getTC002())
                .eq("TC009", "N"));
        if (count1 >= 1) {
            dh = initLldDto.getTC002();
            initMoctcMapper.delete(new QueryWrapper<InitMoctc>()
                    .eq("TC001", initLldDto.getTC001())
                    .eq("TC002", initLldDto.getTC002()));
            initMocteMapper.delete(new QueryWrapper<InitMocte>()
                    .eq("TE001", initLldDto.getTC001())
                    .eq("TE002", initLldDto.getTC002()));
        } else {
            Integer count2 = initMoctcMapper.selectCount(new QueryWrapper<InitMoctc>()
                    .eq("UDF12", initLldDto.getTC002()));
            if (count2 >= 1) {
                return Result.fail("此单号已存在");
            } else {
                flag1 = true;
                dh = commonService.getIdByType(initLldDto.getTC001(), "MOCTC");
                initMoctc.setUdf12(initLldDto.getTC002());
            }
        }
        int flag = 0;

        // 领料单创建人
        String creator = "MES";
        // 领料日期
        String rq = initLldDto.getTC003();
        // 工厂编号
        String gcbh = initLldDto.getTC004();
        //  工作中心
        String gzzx = initLldDto.getTC005();
        //  领料单单别
        String lld = initLldDto.getTC001();
        // 领料工单列表
        List<InitLldList> list = initLldDto.getTeList();

        // 1.判断领料单是否合规

        // 2.判断工单是否合规
        String errorMsg = null;

        if (errorMsg != null) {
            System.out.println(errorMsg);
            return Result.fail(errorMsg);
        }


        String nowTime = TimeUtils.getNowTime();
        // 设置创建者
        initMoctc.setCompany(company);
        initMoctc.setCreator(creator);

        InitAdmmf initAdmmf = initAdmmfMapper.selectOne(new QueryWrapper<InitAdmmf>().eq("MF001", creator));
        System.out.println("admmf:" + initAdmmf.toString());
        initMoctc.setUsrGroup(initAdmmf.getMF004());
        initMoctc.setCreateDate(nowTime);
        initMoctc.setModiDate("");
        initMoctc.setModifier("");
        initMoctc.setFlag((double) (2));

        // 获取领料单单别 对应的信息
        Cmsmq cmsmq = initCmsmqMapper.selectOne(new QueryWrapper<Cmsmq>().eq("MQ001", lld));

        // 领料单对应的年位数
        int yearLength = cmsmq.getMq005().intValue();
        // 获取根据单别获取单号

        initMoctc.setTc001(initLldDto.getTC001());
        initMoctc.setTc002(dh);
        initMoctc.setTc003(rq);
        initMoctc.setTc004(gcbh);
        initMoctc.setTc005(gzzx);
        initMoctc.setTc006(initLldDto.getTC006());
        initMoctc.setTc007("");
        initMoctc.setTc008(initLldDto.getTC008());
        // 设置审核码
        initMoctc.setTc009(initLldDto.getTC009());
        // 设置打印次数
        initMoctc.setTc010((double) 0);
        // 设置生成分录-成本  Y/N
        initMoctc.setTc011("N");
        // 设置 生成排序 1.按工单单号、2.按材料品号
        initMoctc.setTc012("1");
        // 取数方式 Y.需领用量、N.与库存量比较
        initMoctc.setTc013("Y");
        // 设置  单据日期 过来的
        initMoctc.setTc014(initLldDto.getTC014());
        // 设置审核者
        initMoctc.setTc015("");
        // 签核状态码 0.待处理、S.传送中、1.签核中、2.退件、3.已核准、4.撤销审核中、5.作废中、
        // 6.取消作废中、N.不运行电子签核[DEF:"N"]
        initMoctc.setTc016("N");
        // 设置 传送次数
        initMoctc.setTc017((double) 0);
        //   来源别 0.自行输入、1.工单、2.生产入库自动扣料、3.委外进自动扣料、4.委外退自动扣料、
        // 5.开工单、6.委外进厂供料自动扣料、7.委外退厂供料自动扣料 8.批次发料自动退料[DEF:"0"]
        initMoctc.setTc018("0");
        // 设置   来源单别
        initMoctc.setTc019(initLldDto.getTC019());
        // 设置 来源单号
        initMoctc.setTc020(initLldDto.getTC020());
        //moctcMapper.add(moctc);
        // 设置 部门
        // 根据工作中心编号获取 工作中心
        InitCmsmd cmsmd = initCmsmdMapper.selectOne(new QueryWrapper<InitCmsmd>().eq("MD001", gzzx));
        if (cmsmd == null) {
            initMoctc.setTc021("");
        } else {
            initMoctc.setTc021(cmsmd.getMd015().trim());
        }
        // 设置人员编号
        initMoctc.setTc028("");
        initMoctc.setTc031("");
        //log.info("moctc :" + moctc.toString());

        //添加领料单单身

        List<InitMocte> initMoctes = new ArrayList<>();
        int xh = 1;
        double count = 0;
        for (InitLldList lllist : list) {
            // 判断该物料是否领取完成

            //   判断是否存在该物料
            InitMoctb initMoctb = initMoctbMapper.selectOne(new QueryWrapper<InitMoctb>().eq("TB001", lllist.getTE011())
                    .eq("TB002", lllist.getTE012()).
                    eq("TB003", lllist.getTE004()));
            if (initMoctb == null) {
                if (errorMsg == null)
                    errorMsg = "工单单别为: " + lllist.getTE011() + "，  工单单号为" + lllist.getTE012() + "的工单中, 没有物料编号为：" + lllist.getTE004() + "物料信息";
                else errorMsg = "\n" + errorMsg;

                continue;
            }

            // 存在查看库存数量和要领的数量 需要获取工单单身每个物料的仓库
            //物料对应的仓库编号
            String tb009 = lllist.getTE008();
            QueryWrapper<Invmc> invmcQueryWrapper = new QueryWrapper<>();
            invmcQueryWrapper.eq("MC001", lllist.getTE004()).eq("MC002", tb009);
            Invmc invmc = invmcMapper.selectOne(invmcQueryWrapper);
            Double mc007 = new Double(0);
            // 获取库存数量
            if (invmc != null)
                mc007 = invmc.getMc007();
            if (mc007 < lllist.getTE005()) {
                if (errorMsg != null)
                    errorMsg +=
                            "/n" + "工单单别为 ：" + lllist.getTE011() + "，单号为：" + lllist.getTE012() + "，中的需要领料的单号为：" + lllist.getTE004() + "，的产品在仓库中的数量不足!";
                else
                    errorMsg =
                            "工单单别为 ：" + lllist.getTE011() + "，单号为：" + lllist.getTE012() + "，中的需要领料的单号为：" + lllist.getTE004() + "，的产品在仓库中的数量不足!";

                //log.info(errorMsg);
                flag = 3;
                continue;
            }

            // errorMsg 不为空说明 存在库问题 不用在列表中添加
            if (errorMsg != null && flag == 3)
                continue;

            // 仓库库存满足  设置领料单单身
            count += lllist.getTE005();
            InitMocte initMocte = new InitMocte();
            initMocte.setCompany(company);
            initMocte.setCreator(creator);
            initMocte.setUsrGroup(initAdmmf.getMF004());
            initMocte.setCreateDate(nowTime);
            initMocte.setFlag((double) 2);
            initMocte.setTe001(lld);
            initMocte.setTe002(dh);
            initMocte.setTe003(String.format("%04d", xh));
            xh++;
            // 物料品号
            initMocte.setTe004(lllist.getTE004());
            // 领料数量
            initMocte.setTe005(lllist.getTE005());
            // 单位
            initMocte.setTe006(lllist.getTE006());
            // 参考单位
            initMocte.setTe007("");
            // 仓库
            initMocte.setTe008(tb009);
            // 工艺
            initMocte.setTe009("****");
            //批号
            initMocte.setTe010("********************");
            // 工单单别 单号
            initMocte.setTe011(lllist.getTE011());
            initMocte.setTe012(lllist.getTE012());
            // 设置领料说明
            initMocte.setTe013("可用量: " + Math.round(mc007));
            // 备注
            initMocte.setTe015("");
            // 材料类型
            initMocte.setTe016(initMoctb.getTb011());

            initMocte.setTe017(initMoctb.getTb012().trim());
            // 设置材料规格
            initMocte.setTe018(initMoctb.getTb013().trim());
            // 设置审核码
            initMocte.setTe019("N");
            // 设置项目编号
            //mocte.setTE020(moctb.getTB038().trim());
            //mocte.setTE020("********************");
            initMocte.setTe020("");
            // 设置领退料包装数量
            initMocte.setTe021(0.00);
            // 包装单位
            initMocte.setTe022("");
            // 设置批号设置 说明
            initMocte.setTe023("");
            // 设置折算率
            initMocte.setTe024(0.00);
            // 设置库位
            // 获取库位信息

            initMocte.setTe025("##########");
            // 设置库存单位
            Invmb invmb = invmbMapper.selectOne(new QueryWrapper<Invmb>().eq("MB001", lllist.getTE004()));
            initMocte.setTe026(invmb.getMb004().trim());

            // 设置领料库存数量
            initMocte.setTe027(initMocte.getTe005());

            initMocte.setUdf01(invmb.getUdf01());

            // 设置 类型 1.工程品号 2.正式品号[DEF:"2"]
            initMocte.setTec01("2");
            // 设置 核建确认  Y/N[DEF:"N"]
            initMocte.setTeh01("N");
            initMoctes.add(initMocte);
            //log.info(mocte.toString());
        }

        if (errorMsg != null)
            return Result.fail(errorMsg);

        // 设置领料单的领料单头  数量
        initMoctc.setTc029(count);

        // 添加 单头单身
        initMoctcMapper.insert(initMoctc);
        for (InitMocte initMocte : initMoctes) {
            initMocteMapper.insert(initMocte);
        }

        Integer i = initMocteMapper.selectCount(new QueryWrapper<InitMocte>()
                .eq("TE001", lld)
                .eq("TE002", dh));
        if (i == null || i <= 0) {
            initMoctcMapper.delete(new QueryWrapper<InitMoctc>().eq("TC001", lld).eq("TC002", dh));
            return Result.fail("单身生成失败");
        }


        // 判断审核源是否打开
        ShenHe shenHe = new ShenHe();
        //shenHe.setCom(moctc.getCompany());
        shenHe.setCom(company);
        shenHe.setProgram("MOCI03");
        shenHe.setDb(lld);
        shenHe.setDh(dh);
        shenHe.setRq(nowTime.substring(0, 8));
        shenHe.setType("DO");
        shenHe.setUser(creator);

        //String url = "http://" + RunHttp.getIp() + ":9000/api/yifei/audit";
        InetAddress localhost = InetAddress.getLocalHost();
        String ipAddress = localhost.getHostAddress();
        String url = "http://" + ipAddress + ":9000/api/yifei/audit";
        String jsonString = JSON.toJSONString(shenHe);

        String ans = null;

        try {
            ans = HttpClientUtil.postRequest(url, jsonString);
        } catch (IOException e) {
            if (flag1) {
                initMoctcMapper.delete(new QueryWrapper<InitMoctc>().eq("TC001", lld).eq("TC002", dh));
                initMocteMapper.delete(new QueryWrapper<InitMocte>().eq("TE001", lld).eq("TE002", dh));
            }
            //System.out.println("出现异常请查看审批后台是否开启");
            //log.info("出现异常请查看审批后台是否开启");
            System.out.println(e);
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.fail("出现异常请查看审批后台是否开启！");
        }
        HttpResult httpResult = new HttpResult();
        if (ans == null) {
            if (flag1) {
                initMoctcMapper.delete(new QueryWrapper<InitMoctc>().eq("TC001", lld).eq("TC002", dh));
                initMocteMapper.delete(new QueryWrapper<InitMocte>().eq("TE001", lld).eq("TE002", dh));
            }
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.fail("出现异常请查看审批后台是否开启");
        } else {
            System.out.println(ans);
            ans = ans.replace("\\r", "");
            System.out.println("ans :" + ans);
            httpResult = JSON.parseObject(ans, HttpResult.class);
            System.out.println("httpResult: " + httpResult);
            //System.out.println(httpResult.toString());
        }
        if (httpResult.getStatus().equals("失败")) {
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            if (flag1) {
                initMoctcMapper.delete(new QueryWrapper<InitMoctc>().eq("TC001", lld).eq("TC002", dh));
                initMocteMapper.delete(new QueryWrapper<InitMocte>().eq("TE001", lld).eq("TE002", dh));
            }
            return Result.fail("审核失败！\\n" + "原因：" + httpResult.getReason() + "\\n 详情：" + httpResult.getDetail());
        }
        return Result.ok("单据生成成功:" + lld + '_' + dh);
    }

    /**
     * 根据库位插入信息
     */
    private boolean insertByKw(String TF003,String formattedDateTime, MOCTGDto moctg, List<WmsInvml> invmlList, List<WmsInvla> wmsInvlas) {
        String db =moctg.getTG001();
        String creator =moctg.getCreator();
        String userGroup =moctg.getUsrGroup();
        String company =moctg.getCompany();
        String formattedDate = TF003;
        WmsInvla wmsInvla1=wmsInvlaMapper.selectOne(new QueryWrapper<WmsInvla>()
                .eq("LA005",1.0)
                .eq("LA006",moctg.getTG001())//单别
                .eq("LA007",moctg.getTG002())//单号
                .eq("LA008",moctg.getTG003())//序号
                .eq("LA023",moctg.getTG036())//库位
                .eq("LA009",moctg.getTG010())//仓库
                .eq("LA016",moctg.getTG017()));//批号
        if (wmsInvla1 !=null){   // 有就更新
            Double t= wmsInvla1.getLa011()+moctg.getTG011() ;
            wmsInvla1.setLa011(t);//把交易明细信息档里的库存量叠加

            int i=wmsInvlaMapper.update(wmsInvla1,new QueryWrapper<WmsInvla>()
                    .eq("LA005",1.0)
                    .eq("LA006",moctg.getTG001())//单别
                    .eq("LA007",moctg.getTG002())//单号
                    .eq("LA008",moctg.getTG003())//序号
                    .eq("LA023",moctg.getTG036())//库位
                    .eq("LA009",moctg.getTG010())//仓库
                    .eq("LA016",moctg.getTG017()));//批号
            if (i!=1){
                return false;
            }

        }else{    // 没有就新增
            WmsInvla wmsInvla = new WmsInvla();
            wmsInvla.setCompany(company);
            wmsInvla.setCreator(creator);
            wmsInvla.setUsrGroup(userGroup);
            wmsInvla.setCreateDate(formattedDateTime);
//            wmsInvla.setModifier(mocte.getModifier());
//            wmsInvla.setModiDate(mocte.getModiDate());
            wmsInvla.setFlag(1.0);
            wmsInvla.setLa001(moctg.getTG004());//品号
            wmsInvla.setLa004(formattedDate);//日期
//            这四位不能重复
            wmsInvla.setLa005(1.0);//按单据性质的库存影响:减 或 调拨单性质的出写入为-1，其余为+1。
            wmsInvla.setLa006(moctg.getTG001());//单别
            wmsInvla.setLa007(moctg.getTG002());//单号
            wmsInvla.setLa008(moctg.getTG003());//序号
            wmsInvla.setLa009(moctg.getTG010());//仓库
            wmsInvla.setLa010(moctg.getTG020());//备注
            wmsInvla.setLa011(moctg.getTG011());//单据交易库存数量
            wmsInvla.setLa012(0.0);
            wmsInvla.setLa013(0.0);
            wmsInvla.setLa014("1");
            wmsInvla.setLa015("");
            wmsInvla.setLa016(moctg.getTG017());//批号
            wmsInvla.setLa017(0.0);
            wmsInvla.setLa018(0.0);
            wmsInvla.setLa019(0.0);
            wmsInvla.setLa020(0.0);
            wmsInvla.setLa021(0.0);
            wmsInvla.setLa022(formattedDate);//审核时间
            wmsInvla.setLa023(moctg.getTG036());//库位
            wmsInvla.setLa024("");
            wmsInvlas.add(wmsInvla);
            wmsInvlaMapper.insert(wmsInvla);
        }
//            DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
//            String formattedDate = now.format(formatter1);
        WmsInvml wmsInvml = new WmsInvml();
        wmsInvml=wmsInvmlMapper.selectOne(new QueryWrapper<WmsInvml>()
                .eq("ML001",moctg.getTG004())//品号
                .eq("ML002",moctg.getTG010())//仓库
                .eq("ML003",moctg.getTG036())//库位
                .eq("ML004",moctg.getTG017()));//批号
        if (wmsInvml==null){
            wmsInvml = new WmsInvml();
            String uuid = UUID.randomUUID().toString();
            wmsInvml.setUdf12(uuid);
            wmsInvml.setCompany(company);
            wmsInvml.setCreator(creator);
            wmsInvml.setUsrGroup(userGroup);
            wmsInvml.setCreateDate(formattedDateTime);
//                wmsInvml.setModifier(mocte.getModifier());
//                wmsInvml.setModiDate(mocte.getModiDate());
            wmsInvml.setFlag(1.0);
            wmsInvml.setMl001(moctg.getTG004());//品号
            wmsInvml.setMl002(moctg.getTG010());//仓库
            wmsInvml.setMl003(moctg.getTG036());//库位
            wmsInvml.setMl004(moctg.getTG017());//批号
            wmsInvml.setMl005(moctg.getTG011());//库存数量
            wmsInvml.setMl006(moctg.getTG011());//库存包装数量
            wmsInvml.setMl009(formattedDate);//最近入库日
            int i =wmsInvmlMapper.insert(wmsInvml);
            if (i!=1){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }else {
            invmlList.add(wmsInvml);

            Double t= wmsInvml.getMl005()+moctg.getTG011();
            wmsInvml.setMl005(t);//把品号信息档里的库存量加上退料量

            int i=wmsInvmlMapper.update(wmsInvml,new QueryWrapper<WmsInvml>()
                    .eq("ML001",wmsInvml.getMl001())//品号
                    .eq("ML002",wmsInvml.getMl002())//仓库
                    .eq("ML003",wmsInvml.getMl003())//库位
                    .eq("ML004",wmsInvml.getMl004()));//批号
            if (i!=1){
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }

        return true;
    }

}
